
import os
from typing import List
import requests


# 需要到Google Cloud 申请 api-key
GOOGLE_API_KEY = os.getenv("GOOGLE_SEARCH_API_KEY")
# 申请搜索引擎ID，https://programmablesearchengine.google.com/
CX = os.getenv("GOOGLE_SEARCH_ENGINE_ID")

# 网络搜索工具类
class GoogleSearchTool:
    @staticmethod
    def fetch_web_results(query: str, num_results: int = 5) -> List[str]:
        """执行Google搜索并返回格式化结果"""
        url = "https://www.googleapis.com/customsearch/v1"
        params = {
            "key": GOOGLE_API_KEY,
            "cx": CX,
            "q": query,
            "num": num_results
        }

        try:
            response = requests.get(url, params=params, timeout=15)
            results = response.json()
            return [
                f"标题: {item['title']}\n摘要: {item['snippet']}\n链接: {item['link']}"
                for item in results.get("items", [])
            ]
        except Exception as e:
            return [f"搜索失败: {str(e)}"]